package com.xcf.center.client;

import com.xcf.center.ServerMeta;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 服务管理类
 */
public class ServerManager {

    /**
     * key: nameSpace
     * value: 服务元数据列表
     */
    private final Map<String, List<ServerWrapper<ServerMeta>>> serverMetaTable = new ConcurrentHashMap<>();
    private final IBalanceHandler<ServerMeta> balanceHandler;

    private IListener listener;

    public ServerManager() {
        this(new DefaultBalance());
    }

    public ServerManager(IBalanceHandler<ServerMeta> balanceHandler) {
        this.balanceHandler = balanceHandler;
    }

    public void setListener(IListener listener) {
        this.listener = listener;
    }

    public void registerServer(String nameSpace, List<ServerMeta> serverMetas) {
        if (serverMetas == null || serverMetas.isEmpty()) {
            return;
        }
        List<ServerWrapper<ServerMeta>> list = serverMetas.stream().map(ServerWrapper::new).collect(Collectors.toList());
        serverMetaTable.put(nameSpace, list);
        if (null != listener) {
            listener.onChange(nameSpace, list);
        }
    }


    public ServerWrapper<ServerMeta> getServer(String nameSpace) {
        List<ServerWrapper<ServerMeta>> list = serverMetaTable.get(nameSpace);
        if (null == list || list.isEmpty()) {
            return null;
        }
        return balanceHandler.balance(list);
    }

}
